# 作者： 迷路的小怪兽
# 创建时间： 2024/3/26 23:12
import json
from urllib.parse import unquote, quote


class DataToConfig:

    def __init__(self, url, method, headers, data):
        self.url = url
        self.method = method
        self.headers = headers
        self.data = data
        self.result = {}

    def data_to_json(self):
        self.loading_data()
        with open(f'./json/{self.method}_{self.url.split(".com/")[1].split("?")[0].replace("/", "_")}.json', 'w', encoding='utf-8') as fp:
            json.dump(self.result, fp, ensure_ascii=False, indent=4)

    def data_to_yaml(self, data: dict):
        pass

    def loading_data(self):
        self.result['url'] = self.url.split("?")[0]
        self.result['method'] = self.method

        # 请求头不是json格式,直接get
        # self.result['headers'] = self.headers

        Content_Type = self.headers.get('Content-Type', '').lower()
        # POST,application/json解析
        if 'application/json' in Content_Type and self.method.upper() == 'POST':
            if self.data != "" and self.data is not None and self.data != "{}":
                self.result['data'] = json.loads(self.data)
            else:
                self.result['data'] = {'DATA': 'NO JSON DATA'}
        # 用application/x-www-form-urlencoded解析（所有GET和部分POST用这个）
        elif 'application/x-www-form-urlencoded' in Content_Type or self.method.upper() == 'GET':
            self.result['data'] = {}
            # 要加上GET参数为空判断
            if self.method.upper() == 'POST':
                _list = self.data.split('&')
            elif '?' in self.url:
                _list = self.url.split('?', 1)[1].split('&')
            else:
                _list = []
                self.result['data'] = {'DATA': 'NO FORM PARA'}

            for p in _list:
                k, v = p.split('=', 1)
                self.result['data'][k] = unquote(v)


        # 暂不支持
        elif 'multipart/form-data' in Content_Type:
            self.result['data'] = {'DATA': 'can not support multipart param'}


"""
# 使用普通函数，不要使用类，多层会报错
def test_parse(_data):
    data = {}
    if isinstance(_data, dict):
        data = {
            'type': 'obj',
            'properties': {}
        }
        for k, v in _data.items():
            data['properties'][k] = test_parse(v)
    elif isinstance(_data, list):
        data = {
            'type': 'arry',
            'properties': {}
        }
        for n in range(len(_data)):
            data['properties'][str(n)] = test_parse(_data[n])

    elif isinstance(_data, str):
        data = {
            'type': 'string',
            'default': _data
        }

    elif isinstance(_data, int):
        data = {
            'type': 'integer',
            'default': _data
        }

    return data
"""